package cn.windy.samary.module.admin.service.impl;

import cn.windy.samary.module.abstracts.service.impl.AbstractServiceImpl;
import cn.windy.samary.module.admin.common.Tree;
import cn.windy.samary.module.admin.entity.Permission;
import cn.windy.samary.module.admin.entity.RolePermission;
import cn.windy.samary.module.Constants;
import cn.windy.samary.module.admin.mapper.PermissionMapper;
import cn.windy.samary.module.admin.mapper.RolePermissionMapper;
import cn.windy.samary.module.admin.mapper.UserMapper;
import cn.windy.samary.module.admin.service.IPermissionService;
import cn.windy.samary.module.admin.service.IRolePermissionService;
import cn.windy.samary.module.shiro.realm.CustomShiroRealm;
import cn.windy.samary.utils.BuildTree;
import cn.windy.samary.utils.ShiroUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 权限
 *
 * @author zyl
 * @date 2018/5/21 13:31
 */
@Service
public class PermissionServiceImpl extends AbstractServiceImpl<Permission> implements IPermissionService {

    private final static Logger logger = LoggerFactory.getLogger(PermissionServiceImpl.class);

    @Resource
    private PermissionMapper permissionMapper;
    @Resource
    private RolePermissionMapper rolePermissionMapper;
    @Resource
    private IRolePermissionService rolePermissionService;
    @Resource
    private UserMapper userMapper;
    @Resource
    private CustomShiroRealm customShiroRealm;

    public Object getMenu(String userId) {
        if (StringUtils.isNotBlank(userId)) {
            Map<String, Object> map = new HashMap<>();
            map.put("userId", userId);
            map.put("permType", Constants.PERM_TYPE_MENU);
            //查询菜单权限
            List<Permission> permissionList = userMapper.getPermissionByUserId(map);
        }
        return null;
    }

    @Override
    public Tree<Permission> getTree() {
        List<Tree<Permission>> trees = new ArrayList<Tree<Permission>>();
        Subject subject = ShiroUtils.getSubject();
        String userId = ShiroUtils.getUserId();
        Map<String, Object> map = new HashMap<>();
        if (!subject.hasRole(Constants.ROLE_SYSTEM)) {
            map.put("userId", userId);
        }
        map.put("mbType", "mb");
        List<Permission> permissions = userMapper.getPermissionByUserId(map);
        for (Permission p : permissions) {
            Tree<Permission> tree = new Tree<Permission>();
            tree.setId(p.getId());
            tree.setParentId(p.getpId());
            tree.setText(p.getName());
            trees.add(tree);
        }
        Tree<Permission> t = BuildTree.build(trees);
        return t;
    }

    @Override
    public Tree<Permission> getTree(String id) {
        // 根据roleId查询权限
        Map<String, Object> map = new HashMap<>();
        map.put("mbType", "mb");
        //查询所有菜单
        List<Permission> menus = userMapper.getPermissionByUserId(map);
        RolePermission rolePermission = new RolePermission();
        rolePermission.setRoleId(id);
        //查询当前角色所有菜单
        List<RolePermission> select = rolePermissionMapper.select(rolePermission);
        List<String> menuIds = new ArrayList<>();
        select.forEach(menu -> menuIds.add(menu.getPermissionId()));
        for (Permission menu : menus) {
            menuIds.remove(menu.getpId());
        }
        List<Tree<Permission>> trees = new ArrayList<Tree<Permission>>();
        for (Permission m : menus) {
            Tree<Permission> tree = new Tree<Permission>();
            tree.setId(m.getId());
            tree.setParentId(m.getpId());
            tree.setText(m.getName());
            Map<String, Object> state = new HashMap<>(16);
            String menuId = m.getId();
            if (menuIds.contains(menuId)) {
                state.put("selected", true);
            } else {
                state.put("selected", false);
            }
            tree.setState(state);
            trees.add(tree);
        }
        // 默认顶级菜单为０，根据数据库实际情况调整
        Tree<Permission> t = BuildTree.build(trees);
        return t;
    }

    @Override
    public int insertSelective(Permission permission) {
        int i = super.insertSelective(permission);
        //将新增权限和ROLE_SYSTEM关联，roleId:0001
        RolePermission rolePermission = new RolePermission();
        rolePermission.setRoleId("0001");
        rolePermission.setPermissionId(permission.getId());
        int j = rolePermissionService.insertSelective(rolePermission);
        if (j != 0) {
            //刷新权限缓存
            customShiroRealm.clearCachedAuthorizationInfo();
        }

        return i;
    }

    @Override
    public int delete(String id) {
        List<String> ids = new ArrayList<>();
        getChildIds(id, ids);
        ids.add(id);
        int i = permissionMapper.deleteByIdIn(ids);
        Map<String, Object> map = new HashMap<>();
        map.put("permissionIds", ids);
        rolePermissionMapper.deleteBy(map);
        return i;
    }

    public void getChildIds(String pId, List<String> list) {
        List<String> idByPId = permissionMapper.getIdByPId(pId);
        list.addAll(idByPId);
        for (String s : idByPId) {
            getChildIds(s, list);
        }
    }
}
